from flask import Blueprint, render_template, request, redirect, url_for, flash
from db_utils import DbUtils

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        nickname = request.form.get('nickname')
        email = request.form.get('email')

        # 后端验证
        if not all([username, password, nickname, email]):
            flash('所有字段都必须填写', 'danger')
            return render_template('auth/register.html', 
                                username=username,
                                nickname=nickname,
                                email=email)

        db = DbUtils()
        try:
            # 检查用户名是否已存在
            existing_user = db.query("SELECT * FROM users WHERE username = %s", (username,))
            if existing_user:
                flash(f'用户名 "{username}" 已存在，请重新输入。', 'danger')
                return render_template('auth/register.html',
                                    username=username,
                                    nickname=nickname,
                                    email=email)

            # 插入新用户
            db.execute(
                "INSERT INTO users (username, password, nickname, email) VALUES (%s, %s, %s, %s)",
                (username, password, nickname, email)
            )
            flash('注册成功，请登录！', 'success')
            return redirect(url_for('home.login'))  # 注册成功后重定向到登录页面
        except Exception as e:
            flash('注册失败，请重试', 'danger')
            print(f"Registration error: {str(e)}")
            return render_template('auth/register.html',
                                username=username,
                                nickname=nickname,
                                email=email)
        finally:
            db.close()

    return render_template('auth/register.html')